import config from "@/config"
import auth from "@/utils/auth"
export const BaseUrl = config.baseUrl
// 默认配置
const DEFAULT_CONFIG = {
    baseUrl: BaseUrl, // 接口基础地址
    timeout: 60000, // 请求超时时间
    header: {
        'Content-Type': 'application/json',
        'token': auth.getToken() || '',
    }
}

class HttpRequest {
    constructor(config = {}) {
        this.config = {
            ...DEFAULT_CONFIG,
            ...config
        }
        this.interceptors = {
            request: [],
            response: []
        }
    }

    // 核心请求方法
    request(options) {
        // 合并配置
        const mergedOptions = {
            ...this.config,
            ...options,
            url: options.baseUrl ? (options.baseUrl + options.url) : BaseUrl + options.url,
            header: {
                ...this.config.header,
                ...(options.header || {})
            }
        }
        // 请求拦截器
        const chain = [this.sendRequest.bind(this), undefined]
        this.interceptors.request.forEach(interceptor => {
            chain.unshift(interceptor.fulfilled, interceptor.rejected)
        })

        // 响应拦截器
        this.interceptors.response.forEach(interceptor => {
            chain.push(interceptor.fulfilled, interceptor.rejected)
        })

        // 执行链
        let promise = Promise.resolve(mergedOptions)
        while (chain.length) {
            promise = promise.then(chain.shift(), chain.shift())
        }

        return promise
    }

    // 发送请求
    sendRequest(config) {
        return new Promise((resolve, reject) => {
            // 添加超时处理
            const timer = setTimeout(() => {
                reject(new Error(`请求超时!`))
            }, config.timeout)

            uni.request({
                ...config,
                success: (res) => {
                    clearTimeout(timer)
                    resolve(res)
                },
                fail: (err) => {
                    clearTimeout(timer)
                    reject(err)
                }
            })
        })
    }

    // 快捷方法
    get(url, data, options = {}) {
        return this.request({
            url,
            data,
            method: 'GET',
            ...options
        })
    }

    post(url, data, options = {}) {
        return this.request({
            url,
            data,
            method: 'POST',
            ...options
        })
    }

    // 添加请求拦截器
    useRequestInterceptor(fulfilled, rejected) {
        this.interceptors.request.push({
            fulfilled,
            rejected
        })
    }

    // 添加响应拦截器
    useResponseInterceptor(fulfilled, rejected) {
        this.interceptors.response.push({
            fulfilled,
            rejected
        })
    }
}

// 创建实例
const http = new HttpRequest()

// 添加默认响应拦截器（根据项目需求修改）
http.useResponseInterceptor(
    (response) => {
        // 状态码200表示成功
        if (response.data.code === 200) {
            return response.data
        }
        uni.showToast({
            title: response.data.msg || '网络请求失败',
            icon: 'none'
        })
        return response.data
        // return Promise.reject(error)
    },
    (error) => {
        // 统一错误处理
        uni.showToast({
            title: error.message || '网络请求失败',
            icon: 'none'
        })
        return Promise.reject(error)
    }
)

export default http